<?php

namespace app\agent\controller;

use app\common\Common;
use app\common\BaseHelper;

use app\agent\model\Agent as AgentMdl;

use think\Db;
use think\Exception;
use think\Request;

/**
 * 代理商
 */
class Agent extends Base
{

    protected $ifAdd = true; // 是否可以添加代理商

    public function _initialize()
    {

        $this->exceptAction = ['ajaxAgentList', 'parentIdList', 'tenantList', 'openLogList'];
        parent::_initialize();

        if($this->agentInfo){
            // 当前代理商信息
            $this->assign('agentInfo', $this->agentInfo);
            // 代理商级别需大于等于 2
            if($this->agentInfo->level > 2){
                $this->ifAdd = false;
            }
        }

        // 是否可以添加代理商
        $this->assign('ifAdd', $this->ifAdd);
    }

    /**
     * 首页
     *
     * @return mixed
     */
    public function index(){
        // 代理级别
        $agentLevel = $this->getAgentLevel();
        $this->assign('agentLevel', $agentLevel);

        return $this->view->fetch();
    }

    /**
     * Table 列表
     *
     * @return \think\response\Json
     */
    public function ajaxAgentList(){
        $request = $this->request;
        $param = $request->param();
        $model = model($this->model);

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];
        // 排序条件
        $columns = $param['order'][0]['column'];
        $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

        $where = [
            'status' => 1
        ];
        if($this->agentInfo){
            // 当前代理商可见的ID数组
            $ids = $this->getAccessIds();
            $where['id'] = ['in', $ids];
        }
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if($filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
            if($filter['levelId']){
                $where['levelId'] = $filter['levelId'];
            }
            if(isset($filter['district']) && !empty($filter['district'])){
                $where['city'] = ['in', $filter['district']];
            }
            if(isset($filter['start_amount']) && $filter['start_amount']){
                $where['rechargeAmount'] = ['egt', $filter['start_amount']];
            }
            if(isset($filter['end_amount']) && $filter['end_amount']){
                $where['rechargeAmount'] = ['elt', $filter['end_amount']];
            }
            if(isset($filter['start_amount']) && $filter['start_amount'] && isset($filter['end_amount']) && $filter['end_amount']){
                $where['rechargeAmount'] = [['egt', $filter['start_amount']], ['elt', $filter['end_amount']], 'and'];
            }
            if($filter['contactUser']){
                $where['contactUser'] = ['like', '%'.$filter['contactUser'].'%'];
            }
            if($filter['phone']){
                $where['phone'] = ['like', '%'.$filter['phone'].'%'];
            }
        }

        $list = $model->where($where)->limit($start, $length)->order($order)->select();
        $count = $model->where($where)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 上级代理 ID
     * @return \think\response\Json
     */
    public function parentIdList(){
        $request = $this->request;
        $param = $request->param();
        $model = model($this->model);

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];

        $where = [
            'status' => 1
        ];
        if(!empty($param['id'])){
            $where['id'] = ['neq', $param['id']];
        }
        if(!empty($param['levelId'])){
            $levelIds = $this->getAccessLevelIds($param['levelId']);

            $where['levelId'] = ['in', $levelIds];
        }
        if($this->agentInfo){
            // 当前代理商可见的ID数组
            $ids = $this->getAccessIds();
            $where['id'] = ['in', $ids];
        }
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if($filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
            if(isset($filter['levelId']) && !empty($filter['levelId'])){
                $levelIds = $this->getAccessLevelIds($filter['levelId']);

                $where['levelId'] = ['in', $levelIds];
            }
        }

        $list = $model->where($where)->limit($start, $length)->select();
        $count = $model->where($where)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 开通商户 列表
     * @return \think\response\Json
     */
    public function tenantList(){
        $request = $this->request;
        $param = $request->param();
        $model = model('Tenant');

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];

        if(empty($param['id'])){
            $result = [
                'status' => '0',
                'draw' => $param['draw'],
                'data' => [],
                'recordsFiltered' => 0,
                'recordsTotal' => 0,
            ];
            return json($result);
        }
        $where = [
            //'a.isActive' => 1,
            'createOper' => $param['id']
        ];

        $list = $model->alias('a')->where($where)->limit($start, $length)->select();
        $count = $model->alias('a')->where($where)->count();
        foreach ($list as &$item) {
            $user = db('operator')->where(['tenantId' => $item->id, 'storeId' => 0, 'roleType' => 0])->field('loginName')->find();
            $item->loginName = $user['loginName'];
            $agent = db('agent')->where(['id' => $item->createOper])->field('name')->find();
            $item->agentName = $agent['name'];
        }

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 开通记录 列表
     * @return \think\response\Json
     */
    public function openLogList(){
        $request = $this->request;
        $param = $request->param();
        $model = model('Agentopenlog');

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];

        if(empty($param['id'])){
            $result = [
                'status' => '0',
                'draw' => $param['draw'],
                'data' => [],
                'recordsFiltered' => 0,
                'recordsTotal' => 0,
            ];
            return json($result);
        }
        $where = [
            'a.agentId' => $param['id']
        ];

        $join = [
            ['__AGENT__ ag', 'a.agentId = ag.id'],
            ['__TENANT__ t', 'a.tenantId = t.id'],
        ];
        $field = 'a.*, t.code, t.name';
        $list = $model->alias('a')->where($where)->limit($start, $length)->join($join)->field($field)->select();
        $count = $model->alias('a')->where($where)->join($join)->field($field)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 添加
     *
     * @return mixed
     */
    public function add(){
        // 代理级别
        $agentLevel = $this->getAgentLevel();
        $this->assign('agentLevel', $agentLevel);

        return $this->view->fetch();
    }

    /**
     * 添加提交
     *
     * @return \think\response\Json
     */
    public function addPost(){
        $request = $this->request;
        if($this->request->isAjax()) {
            $model = model($this->model);
            $data = $this->request->param();
            // Insert data
            $data['id'] = BaseHelper::getUUID();
            $data['createDate'] = time();
            $data['createOper'] = $this->admin->id;
            $data['fullAddress'] = $data['province'] . ' ' . $data['city'] . ' ' . $data['district'];
            //$data['rechargeAmount'] = $data['rechargeAmount'] ? $data['rechargeAmount'] * 100 : '';
            // 预存金额（万元）
            $data['rechargeAmount'] = $this->getReserveAmount($data['levelId']);
            $data['openNumber'] = $this->countOpenNumber($data);

            try {
                Db::startTrans();
                // 是否可以开下级代理
                // TODO 总管理员需要判断吗？（目前没有判断）
                if($this->agentInfo){
                    if($this->agentInfo->rechargeAmount < $data['rechargeAmount']){
                        return json(['status' => 0, 'msg' => '当前余额不够开下级代理，请先充值！']);
                    }
                }
                // 账号名检查
                if($this->checkName($data['loginName'])){
                    return json(['status' => 0, 'msg' => '该账号名已存在！']);
                }
                $result = $model->save($data);

                if($result !== false) {
                    // 添加下级代理 减去费用
                    $this->handleAgent($data['rechargeAmount']);
                    // 代理商用户
                    $userData = [
                        'id' => '',
                        'createDate' => time(),
                        'agentId' => $data['id'],
                        'loginName' => $data['loginName'],
                        'password' => BaseHelper::passwordEncrypt($data['password']),
                        'phone' => $data['phone'],
                        'userType' => 1
                    ];
                    $res = $this->handleAgentUser($userData);
                    if($res){
                        Db::commit();
                        // 写入日志
                        $logInfo = $this->admin->loginName . '添加了一条' . $this->model . '数据。';
                        common::agentLog($request, $logInfo);

                        return json(['status' => 1, 'msg' => '添加成功！']);
                    }else{
                        Db::rollback();
                        return json(['status' => 0, 'msg' => '添加失败！']);
                    }
                } else {
                    return json(['status' => 0, 'msg' => '添加失败！']);
                }
            } catch (Exception $e) {
                return json(['status' => 0, 'msg' => $e->getMessage()]);
            }
        } else {
            return json(['status' => 0, 'msg' => '请求方式不正确！']);
        }
    }

    /**
     * 编辑
     *
     * @return mixed
     */
    public function edit(){
        $model = model($this->model);
        $id = $this->request->param('id');
        $where = [
            'a.id' => $id,
        ];
        $join = [
            ['__AGENTUSER__ u','a.id = u.agentId'],
        ];
        $field = 'a.*, u.id as userId, u.loginName, u.password';
        $info = $model->alias('a')->where($where)->join($join)->field($field)->find();
        $parent = $model->where(['id' => $info->parentId])->field('name')->find();
        if($parent){
            $info->parentName = $parent->name;
        }

        if(!$info){
            return $this->error('error !', 'agent/agent/index');
        }
        // 代理级别
        $agentLevel = $this->getAgentLevel();
        $this->assign('agentLevel', $agentLevel);
        $this->assign('title', "【{$info['levelName']}】 {$info['name']}");
        $this->assign('info', $info);

        return $this->view->fetch();
    }

    /**
     * 编辑提交
     */
    public function editPost(){
        $request = $this->request;
        if($this->request->isAjax()) {
            $model = model($this->model);
            $data = $this->request->param();
            // Update data
            $data['updateDate'] = time();
            $data['updateOper'] = $this->admin->id;
            $data['fullAddress'] = $data['province'] . ' ' . $data['city'] . ' ' . $data['district'];

            try {
                Db::startTrans();
                if($this->checkName($data['loginName'], $data['userId'])){
                    return json(['status' => 0, 'msg' => '该账号名已存在！']);
                }
                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

                if($result !== false) {
                    // 代理商用户
                    $userData = [
                        'id' => $data['userId'],
                        'updateDate' => time(),
                        'agentId' => $data['id'],
                        'loginName' => $data['loginName'],
                        'phone' => $data['phone'],
                        'userType' => 1
                    ];
                    if(trim($data['password']) && $data['password'] != $data['ori_password']){
                        $userData['password'] = BaseHelper::passwordEncrypt($data['password']);
                    }
                    $res = $this->handleAgentUser($userData);

                    if($res){
                        Db::commit();
                        // 写入日志
                        $logInfo = $this->admin->loginName . '更新了一条' . $this->model . '数据。';
                        common::agentLog($request, $logInfo);

                        return json(['status' => 1, 'msg' => '保存成功！']);
                    }else{
                        Db::rollback();
                        return json(['status' => 0, 'msg' => '保存失败！']);
                    }
                } else {
                    return json(['status' => 0, 'msg' => '保存失败！']);
                }
            } catch (Exception $e) {
                return json(['status' => 0, 'msg' => $e->getMessage()]);
            }
        } else {
            return json(['status' => 0, 'msg' => '请求方式不正确！']);
        }
    }

    /**
     * 详情
     *
     * @return mixed
     */
    public function view(){
        $model = model($this->model);
        $id = $this->request->param('id');
        $where = [
            'a.id' => $id,
        ];
        $info = $model->alias('a')->where($where)->find();

        if(!$info){
            return $this->error('error !', 'agent/agent/index');
        }
        $this->assign('title', "【{$info['levelName']}】 {$info['name']}");
        $this->assign('info', $info);

        return $this->view->fetch();
    }

    /**
     * 获取当前代理商可见的 ID 数组
     */
    public function getAccessIds(){
        $ids = [$this->agentId];
        switch($this->agentInfo->level){
            case 1:
                // 省级代理 -- 可见下级市级代理 & 可见下级经销商 （不可见想下级市级代理的下级经销商）
                $agentDB = db('Agent');
                // 下级市级代理
                $childs = $agentDB->where(['parentId' => ['in', $this->agentId]])->field('id')->select();
                /*
                $childsIds = array_column($childs, 'id');
                $childs2Ids = [];
                foreach ($childsIds as $childsId) {
                    $childs2 = $agentDB->where(['parentId' => ['in', $childsId]])->field('id')->select();
                    $childs2Ids = array_merge($childs2Ids, array_column($childs2, 'id'));
                }
                $ids = array_merge($childsIds, $childs2Ids);
                */
                $ids = array_column($childs, 'id');
                $ids[] = $this->agentId;
                break;
            case 2:
                // 市级代理 -- 可见下级经销商
                $childs = db('Agent')->where(['parentId' => ['in', $this->agentId]])->field('id')->select();
                if($childs){
                    $ids = array_column($childs, 'id');
                    $ids[] = $this->agentId;
                }
                break;
            case 3:
                // 经销商
                break;
            default : break;
        }

        return $ids;
    }

    /**
     * 代理级别
     */
    public function getAgentLevel(){
        $where = [];
        if($this->agentInfo){
            switch($this->agentInfo->level){
                case 1:
                    // 省级代理
                    //$where['level'] = ['in', '1, 2, 3'];
                    $where['level'] = ['in', '2, 3'];
                    break;
                case 2:
                    // 市级代理
                    //$where['level'] = ['in', '2, 3'];
                    $where['level'] = ['in', '3'];
                    break;
                case 3:
                    // 经销商
                    $where['level'] = 3;
                    break;
                default : break;
            }
        }
        $agentLevel = db('agentpolicy')->where($where)->order('level', 'ASC')->select();

        return $agentLevel;
    }

    /**
     * 根据当前选中的代理级别 得到允许的所属上级的 ID 数组
     */
    public function getAccessLevelIds($levelId){
        $agentpolicyDB = db('agentpolicy');
        $agentpolicy = $agentpolicyDB->where(['id' => $levelId])->field('level')->find();
        $levelIds = [];
        switch($agentpolicy['level']){
            case 1:
                // 省级代理 -- 没有上级
                $levelIds[] = 0;
                break;
            case 2:
                // 市级代理 -- 上级为 省级代理
                $agentpolicy = $agentpolicyDB->where(['level' => 1])->field('id')->find();
                $levelIds[] = $agentpolicy['id'];
                break;
            case 3:
                // 经销商 -- 上级为 省级代理 & 市级代理
                $agentpolicy = $agentpolicyDB->where(['level' => ['in', '1, 2']])->field('id')->select();
                $levelIds = array_column($agentpolicy, 'id');
                break;
            default : break;
        }

        return $levelIds;
    }

    /**
     * 根据代理级别获取代理商的预存金额
     */
    public function getReserveAmount($levelId){
        if($levelId){
            $agentpolicy = db('agentpolicy')->where(['id' => $levelId])->field('reserveAmount')->find();

            return $agentpolicy['reserveAmount'];
        }else{
            return 0;
        }
    }

    /**
     * 计算 可以开通商户的数量
     */
    public function countOpenNumber($data){
        if(!$data){
            return 0;
        }
        if(isset($data['levelId']) && !empty($data['levelId'])){
            $agentpolicy = db('agentpolicy')->where(['id' => $data['levelId']])->field('buyingPrice')->find();
            $number = intval($data['rechargeAmount'] / $agentpolicy['buyingPrice']);

            return $number;
        }else{
            return 0;
        }
    }

    /**
     * 代理商 添加下级代理 减去费用
     */
    public function handleAgent($rechargeAmount){
        if(!$rechargeAmount){
            return false;
        }

        if(!$this->agentInfo){
            return false;
        }

        try {
            $model = model('Agent');
            // 开户费用
            $openAccountCost = $rechargeAmount;
            $result = $model->where(['id' => $this->agentInfo->id])->setDec('rechargeAmount', $openAccountCost);

            if($result !== false){
                return true;
            }else{
                return false;
            }
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 代理商后台管理员
     */
    public function handleAgentUser($data){
        if(!$data){
            return false;
        }

        try {
            $model = model('Agentuser');
            if($data['id']){
                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
            }else{
                $data['id'] = BaseHelper::getUUID();
                $result = $model->save($data);
            }

            if($result !== false){
                return true;
            }else{
                return false;
            }
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 检查用户名是否已存在
     */
    public function checkName($loginName, $id = ''){
        //$loginName = $this->request->param('loginName');
        $agentuserDB = db('Agentuser');
        if($id){
            $info = $agentuserDB->where(['id' => $id])->field('loginName')->find();
            if($info['loginName'] == $loginName){
                return false;
            }
        }
        $admin = $agentuserDB->where(['loginName' => $loginName, 'status' => 1])->field('loginName')->find();

        if($admin){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 充值
     */
    public function recharge(){
        $id = $this->request->param('id');
        if(!$id){
            return json(['status' => 0, 'msg' => '参数错误！']);
        }

        $model = model($this->model);
        $info = $model->where(['id' => $id])->find();
        if(!$info){
            return json(['status' => 0, 'msg' => '该商户不存在！']);
        }

        $agent = db('agent')->where(['id' => $info->createOper])->field('name')->find();
        $info->agentName = $agent['name'];

        $this->assign('info', $info);

        return json(['status' => 1, 'data' => $this->fetch('')]);
    }

    /**
     * 充值提交
     */
    public function rechargePost(){
        $request = $this->request;
        if($this->request->isAjax()){
            $id = $this->request->param('id');
            if(!$id){
                return json(['status' => 0, 'msg' => '参数错误！']);
            }

            $model = model($this->model);
            $info = $model->where(['id' => $id])->find();
            $recharge = $this->request->param('recharge_money');
            $rechargeAmount = $info['rechargeAmount'] + ($recharge * 100);
            $levelId = $this->request->param('levelId');
            $data = [
                'rechargeAmount' => $rechargeAmount,
                'openNumber' =>$this->countOpenNumber(['levelId' => $levelId, 'rechargeAmount' => $rechargeAmount])
            ];
            $result = $model->save($data, ['id' => $id]);
            if($result !== false){
                // 写入日志
                $logInfo = $this->admin->loginName . '充值了1条' . $this->model . '数据。';
                common::agentLog($request, $logInfo);

                return json(['status' => 1, 'msg' => '充值成功！']);
            }else{
                return json(['status' => 0, 'msg' => '充值失败！']);
            }
        }
    }

    /**
     * 删除
     */
    public function delete(){
        $request = $this->request;
        if($this->request->isAjax()) {
            $model = model($this->model);
            $id = $this->request->param('id');

            try {
                Db::startTrans();
                $info = $model->find(['id', $id]);
                if(!$info){
                    return json(['status' => 0, 'msg' => '该代理商不存在！']);
                }
                $result = $model->save(['status' => 2], ['id' => $id]);

                if($result !== false) {
                    $res = db('agentuser')->where(['agentId' => $id])->update(['status' => 2]);
                    if($res){
                        Db::commit();
                        // 写入日志
                        $logInfo = $this->admin->loginName . '删除了1条' . $this->model . '数据。';
                        common::agentLog($request, $logInfo);

                        return json(['status' => 1, 'msg' => '删除成功！']);
                    }else{
                        Db::rollback();
                        return json(['status' => 0, 'msg' => '删除失败！']);
                    }
                } else {
                    return json(['status' => 0, 'msg' => '删除失败！']);
                }
            } catch (Exception $e) {
                return json(['status' => 0, 'msg' => $e->getMessage()]);
            }
        } else {
            return json(['status' => 0, 'msg' => '请求方式不正确！']);
        }
    }

}